<template>
  <div class="defaultPermission">
    <a-card :bordered="false">
      <!-- 表格部分 -->
      <c-table
        :columns="tableColumns"
        :datas="tableData"
        :loading="loading"
        showPagination
        :paginationDatas="paginationDatas"
        @onPageSizeChange="onPageSizeChange"
        @onShowNumChange="onShowNumChange"
      >
        <!-- 表格自定义部分 -->
        <template slot="companyDirection" slot-scope="row">
          <a-tag v-if="row.tableRow" :color="$dealDic(businessDirection,row.tableRow,'tagColor')">
           {{$dealDic(businessDirection,row.tableRow,'label')}}
          </a-tag>
          <span v-else>-</span>
        </template>
        <!-- 表格操作按钮 -->
        <template slot="handle" slot-scope="row">
          <a-space>
            <!-- 查看 -->
            <div class="display-inline">
              <a @click="onView(row.tableRow)">
                <a-icon type="eye" />查看
              </a>
            </div>
            <!-- 编辑 -->
            <div class="display-inline">
              <a-divider type="vertical" />
              <a @click="onEdit(row.tableRow)">
                <a-icon type="edit" />编辑
              </a>
              <!-- <a v-else class="textGrey"> <a-icon type="edit" />编辑 </a> -->
            </div>
          </a-space>
        </template>
      </c-table>
    </a-card>
    <a-drawer
      title="编辑默认权限"
      :visible="visible"
      :width="'30%'"
      @ok="onOk"
      :body-style="{ paddingBottom: '80px' }"
      @close="onCancel"
      :destroyOnClose="true"
    >
      <c-form-model
        :datas="formData"
        :rules="rules"
        @onTreeCheck="onTreeCheck"
        checkStrictly
        v-model="form"
        ref="formModels"
      ></c-form-model>
      <div class="drawer-footer-btn flex-center">
        <a-button class="margin-r10" @click="onCancel">取消</a-button>
        <a-button type="primary" :loading="confirmLoading" @click="onOk">确定</a-button>
      </div>
    </a-drawer>
  </div>
</template>
<script>
import { mapActions } from "vuex";
import {
  getdefaultpermissions,
  editdefaultpermissions
} from "@/api/mallSystem/defaultPermission";
import { getBaseResourceByDirection } from "@/api/resource";
import { getParent, findChildIdArr } from "@/util/common";
import { businessDirection } from "@/dict/public";

export default {
  name: "defaultPermission",
  components: {},
  data() {
    return {
      loading: false,
      businessDirection,
      tableData: [],
      tableColumns: [
        {
          title: "默认角色名称",
          dataIndex: "roleName",
          key: "roleName",
          align: "center"
        },
        {
          title: "业务方向",
          dataIndex: "companyDirection",
          key: "companyDirection",
          scopedSlots: { customRender: "companyDirection" },
          align: "center"
        },
        {
          title: "操作",
          key: "handle",
          scopedSlots: { customRender: "handle" },
          align: "center",
          width: 160
        }
      ],
      confirmLoading: false,
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        companyDirection: [
          { required: true, message: "请输入业务方向", trigger: "change" }
        ]
      },
      openType: "edit",
      permissionSetDataList: [],
      form: {
        roleName: "",
        companyDirection: 1,
        resourceIds: []
      },
      paginationDatas: {
        pageSizeOptions: ["10", "20", "30", "40", "50", "200", "1000"],
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      visible: false
    };
  },
  computed: {
    formData() {
      let res = [
        {
          label: "角色名称",
          prop: "roleName",
          disabled: true
        },
        {
          label: "业务方向",
          prop: "companyDirection",
          type: "select",
          typeData: businessDirection,
          disabled: true
        },
        {
          label: "权限设置",
          prop: "resourceIds",
          type: "tree",
          typeData: this.permissionSetDataList,
          replaceFields: {
            children: "children",
            title: "resourceName",
            key: "id"
          },
          disabled: this.openType == "view" ? true : false
        }
      ];
      return res;
    }
  },
  created() {
    this.onPageOnlod();
    //根据业务方向获取权限资源
    this.getPageResourceList();
  },
  methods: {
    ...mapActions(["getBaseResourceListByDirection"]),
    getParent,
    findChildIdArr,
    getPageResourceList() {
      let parmas = {
        companyDirection: this.form.companyDirection
      };
      this.getBaseResourceListByDirection(parmas).then(res => {
        this.permissionSetDataList = res;
      });
    },
    //弹窗树操作
    onTreeCheck(checkedKeys, eventKey, checked) {
      let idArr = [];
      if (checked) {
        checkedKeys.map(id => {
          return getParent(this.permissionSetDataList, id).map(item => {
            return idArr.push(item.id);
          });
        });
      } else {
        let deleteArr = findChildIdArr(this.permissionSetDataList, eventKey);
        idArr = checkedKeys;
        idArr = idArr.filter(item => {
          let idList = deleteArr.map(v => v);
          return !idList.includes(item);
        });
      }
      this.$refs.formModels.changeTreeCheck([...new Set(idArr)]);
    },
    //初始化页面
    onPageOnlod() {
      this.loading = true;
      getdefaultpermissions({
        ...{
          pageSize: this.paginationDatas.pageSize,
          pageNum: this.paginationDatas.pageNum
        }
      })
        .then(res => {
          if (!res.data) res.data = {};
          if (!res.data.pageData) res.data.pageData = [];
          this.tableData = res.data.pageData;
          this.paginationDatas.total = res.data.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //预览
    onView(row) {
      this.openType = "view";
      this.echoData(row);
    },
    //编辑
    onEdit(row) {
      this.openType = "edit";
      this.echoData(row);
    },
    //弹窗数据回显
    echoData(row) {
      this.permissionSetDataList = [];
      for (const key in this.form) {
        if (row[key]) {
          this.form[key] = row[key];
          this.form.id = row.id;
        }
        this.form.resourceIds = row.resources.map(i => i.resourceId);
      }
      this.visible = true;
      this.getPageResourceList();
    },
    //编辑提交
    onOk() {
      const that = this;
      this.$refs.formModels.handleValidate().then(data => {
        const parmas = {
          roleId: data.id,
          resourceIds: data.resourceIds
        };
        that.confirmLoading = true;
        editdefaultpermissions(parmas)
          .then(res => {
            that.$message.success("操作成功");
            that.onPageOnlod();
            that.confirmLoading = false;
            that.visible = false;
          })
          .catch(() => {
            this.confirmLoading = false;
          });
      });
    },
    onShowNumChange(val) {
      this.paginationDatas.pageNum = val;
      this.onPageOnlod();
    },
    onPageSizeChange(val) {
      this.paginationDatas.pageSize = val;
      this.onPageOnlod();
    },
    //取消
    onCancel() {
      this.visible = false;
      this.confirmLoading = false;
    }
  }
};
</script>
<style lang="less" scoped>
::v-deep td.text-left {
  text-align: left !important;
}
</style>
